package com.zy.servlet.yhgl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhang.sys.SysGroup;
import com.zhang.sys.SysGroupDAO;
import com.zy.service.GroupService;

public class GetGroupMenu extends HttpServlet {

	private static final Logger log = LoggerFactory
			.getLogger(GetGroupMenu.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("appliaction/x-json;charset=utf-8");
		PrintWriter out = response.getWriter();
		String orgId = request.getParameter("id");

		SysGroupDAO dao = new SysGroupDAO();
		if (orgId == null || orgId.equals("")||"rootNode".equals(orgId)) {
			orgId = "1";
		}
		List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
		List<SysGroup> userlist = new ArrayList<SysGroup>();
		SysGroup user = new SysGroup();
		userlist = dao.findByGroupParentId(orgId);
		for (int i = 0; userlist != null && i < userlist.size(); i++) {
			Map<String, Object> m = new HashMap<String, Object>();
			user = userlist.get(i);
			m.put("id", user.getGroupId());
			m.put("text", user.getGroupName());
			m.put("iconCls", "group-icon");
			m.put("expanded", false);
			int gs = dao.countGroupByGroup(user.getGroupId());
			if(gs>0){
				m.put("leaf", false);
			}else{
				m.put("leaf", true);
			}
			list1.add(m);
		}
	
		dao.getSession().close();
		JSONArray obj = JSONArray.fromObject(list1);
		out.println(obj.toString());
		out.flush();
		out.close();
	}

}
